# -*- coding: utf-8 -*-
import base64

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES


class PrpCrypt(object):

    def __init__(self, key, vi='0000000000000000'):
        self.key = key.encode('utf-8')
        self.mode = AES.MODE_CBC
        self.vi = vi.encode('utf-8')

    # 加密函数，如果text不足16位就用空格补足为16位，
    # 如果大于16当时不是16的倍数，那就补足为16的倍数。
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.vi)
        text = text.encode('utf-8')

        # 这里密钥key 长度必须为16（AES-128）,
        # 24（AES-192）,或者32 （AES-256）Bytes 长度
        # 目前AES-128 足够目前使用

        text = self.pkcs7_padding(text)

        self.ciphertext = cryptor.encrypt(text)

        # 因为AES加密时候得到的字符串不一定是ascii字符集的，输出到终端或者保存时候可能存在问题
        # 所以这里统一把加密后的字符串转化为16进制字符串
        return str(base64.encodebytes(self.ciphertext), encoding='utf-8').replace('\n', '')
        # return str(base64.encodebytes(self.ciphertext), encoding='utf-8')

    @staticmethod
    def pkcs7_padding(data):
        if not isinstance(data, bytes):
            data = data.encode()
        pad_pkcs7 = pad(data, AES.block_size, style='pkcs7')  # 选择pkcs7补全
        return pad_pkcs7

    @staticmethod
    def pkcs7_unpadding(padded_data):
        pad_pkcs7 = unpad(padded_data, AES.block_size, style='pkcs7')  # 选择pkcs7补全
        return pad_pkcs7

    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        encode = text.encode('utf-8')
        text = base64.decodebytes(encode)
        # 偏移量
        cryptor = AES.new(self.key, self.mode, self.vi)
        plain_text = cryptor.decrypt(text)
        plain_text = self.pkcs7_unpadding(plain_text)
        return plain_text.decode("utf-8")

    @staticmethod
    def encrypt_password(username, password):
        key = PrpCrypt.pkcs7_padding(username)
        crypt = PrpCrypt(key.decode('utf-8'))
        return crypt.encrypt(password)

    @staticmethod
    def decrypt_password(username, password):
        key = PrpCrypt.pkcs7_padding(username)
        crypt = PrpCrypt(key.decode('utf-8'))
        return crypt.decrypt(password)

    
if __name__ == '__main__':
    ret = PrpCrypt('di3xcAWSbBYbMxfL', 'E3E5nc8Garay7msN').encrypt(
        'jh5AdrAyZNYiGSPxTrTWmWDK8jbMpKssZPdMN4DYzSJJ2Q6AJ8rajHstatw5yeiYLhy6323886@')
    print(ret)
    # ret1 = PrpCrypt('YTa1dyHcOPVZsOcb', '1111111111111111').decrypt("QRxFADfbdDmibfkexB3PnNJ5fwnfb77mK6kWe5N863KaiBEmAQX4mRGX3Sb6XcXMLhy6323886@1")
    # print(ret1)
    "9DWNTG2p6d1FpGGkL4EZptVZcdHEsNKtfnsoJugYkRpBYMhsP46AFly+1ELdIdACPA0pwF3F8XMBqjbMBn6Jljz028TqXrpKh9tG2xU8cHc="
